package com.medic.client.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.medic.entity.User;
import com.medic.entity.Weichat;
import com.medic.entity.group.pain.Alert;
import com.medic.entity.group.pain.Medic;
import com.medic.service.impl.MedicServiceImpl;
import com.medic.util.CacheUtil;
import com.medic.util.LoggerUtil;
import com.medic.util.StringUtil;

@Controller
@RequestMapping("/client/medic")
@SessionAttributes({ "user", "weichat" })
public class MedicController {

	@Resource(name = "medicService")
	private MedicServiceImpl medicService;

	private final String medicKey = "medic";
	private final String medicsKey = "medics";
	private final String msgKey = "msg";

	@RequestMapping("/queryDetail")
	public String query(@ModelAttribute("user") User user, int medicId, Model model) {
		String result = "";
		try {
			if (medicId > 0) {
				for (Map.Entry<Integer, Medic> entry : CacheUtil.getMedics().entrySet()) {
					if (entry.getKey() == medicId && user.getId() == entry.getValue().getSikerId()) {
						model.addAttribute(medicKey, entry.getValue());
						break;
					}
				}
			}
			result = "/client/take-medic-alert-add";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + "params : [ userId : " + user.getId() + ",medicId : "
					+ medicId + " ]");
			result = "error";
		}
		return result;
	}

	@RequestMapping("/queryList")
	public String query(@ModelAttribute("user") User user, Model model) {
		String result = "";
		try {
			List<Medic> list = new ArrayList<Medic>();
			for (Map.Entry<Integer, Medic> entry : CacheUtil.getMedics().entrySet()) {
				if (user.getId() == entry.getValue().getSikerId()) {
					LoggerUtil.debug(entry.getValue().toString());
					list.add(entry.getValue());
				}
			}
			model.addAttribute(medicsKey, list);
			result = "/client/take-medic-info";
		} catch (Exception e) {
			result = "error";
		}
		return result;
	}

	/**
	 * 添加、修改用药提醒（修改就是先添加新的 然后将原来的删掉）
	 * 
	 * @param user
	 *            用户
	 * @param weichat
	 *            微信账号
	 * @param medic
	 *            药品
	 * @param alertTime
	 *            提醒时间
	 * @param amounts
	 *            剂量
	 * @param model
	 * @return
	 */
	@RequestMapping("/add")
	public String add(@ModelAttribute("user") User user, @ModelAttribute("weichat") Weichat weichat, Medic medic,
			String alertTime, String amounts, Model model) {
		String result = "";
		int medicId = 0;
		try {
			medic.setSikerId(user.getId());
			medic.setOpenId(weichat.getOpenid());
			if (medic.getMedicId() > 0) {
				medicId = medic.getMedicId();
				Medic object = CacheUtil.getMedics().get(medicId);
				medic.setMedicName(object.getMedicName());
				medic.setMedicUnit(object.getMedicUnit());
				medic.setTakeType(object.getTakeType());
			} 
			LoggerUtil.debug(medic.toString() + "------------------" + alertTime + "-------------" + amounts);
			String[] alerT = alertTime.trim().split(",");
			String[] amo = amounts.trim().split(",");
			List<Alert> alerts = new ArrayList<Alert>();
			Alert alert = null;
			for (int i = 0; i < amo.length; i++) {
				alert = new Alert();
				alert.setAlertTime(alerT[i]);
				alert.setAmounts(Integer.parseInt(amo[i]));
				alerts.add(alert);
			}
			medic.setAlert(alerts);
			if (medicId > 0) {
				// 删除数据库中原来存在的
				CacheUtil.getMedics().remove(medicId);
				Medic object = new Medic();
				object.setMedicId(medicId);
				object.setSikerId(user.getId());
				medicService.delete(object);
			}
			if (medicService.save(medic)) {
				CacheUtil.getMedics().put(medic.getMedicId(), medic);
				model.addAttribute(msgKey, "保存成功");
			} else {
				model.addAttribute(msgKey, "保存失败");
			}
			result = "result";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ userId : " + user.getId() + ",openId : "
					+ weichat.getOpenid() + ",Medic : " + medic + ",alertTime : " + alertTime + ",amouts : " + amounts
					+ " ]");
			result = "error";
		}
		return result;
	}

	@RequestMapping("/delete")
	public String delete(@ModelAttribute("user") User user, int medicId, Model model) {
		String result = "";
		Medic medic = CacheUtil.getMedics().get(medicId);
		try {
			medic.setSikerId(user.getId());
			if (!medic.getMedicName().equals(StringUtil.MEDIC_NAME) && medicService.delete(medic)) {
				CacheUtil.getMedics().remove(medicId);
				model.addAttribute(msgKey, "删除成功");
			} else {
				model.addAttribute(msgKey, "删除失败");
			}
			result = "result";
		} catch (Exception e) {
			LoggerUtil.error("error : " + e.getMessage() + " - params : [ medic : " + medic + " ]");
			result = "error";
		}
		return result;
	}
}
